package com.sumainfor.wx.system.maket.service;

import com.google.common.collect.Lists;
import com.sumainfor.common.Constants;
import com.sumainfor.common.ConstantsHousing;
import com.sumainfor.common.entity.ParentDeptVo;
import com.sumainfor.common.entity.SysUserVo;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.wx.system.feign.BaseFeignTenant;
import com.sumainfor.wx.system.feign.BaseFeignZuul;
import com.sumainfor.wx.system.maket.dao.RdTenantMapper;
import com.sumainfor.wx.system.maket.dao.RdWorderInfoMapper;
import com.sumainfor.wx.system.maket.dao.RdWorderMapper;
import com.sumainfor.wx.system.maket.dao.UtilsMapper;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * <p>
 * 租赁顾问
 * <p>
 *
 * @author: zc
 * @create: 2019-08-07 10:20
 **/
@Service
public class RdWorderService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdWorderService.class);// 日志

    @Autowired
    RdWorderMapper rdWorderMapper;


    @Autowired
    BaseFeignZuul baseFeignZuul;


    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    RdTenantMapper rdTenantMapper;


    @Autowired
    BaseFeignTenant baseFeignTenant;

    @Autowired
    RdWorderInfoMapper rdWorderInfoMapper;

    String UUID =null;



  /**
   *  查询今日需带看
   * @author zhoucong
   * @data 2019/8/7
   * @Param
   * @return
   */
  public List<Map<String,Object>> getWorderListToday(Map<String,Object> params){

      List<Map<String,Object>> getWorderListToday = rdWorderMapper.getWorderListToday(params);
      getWorderListToday.stream().map(
              item ->{
                  //处理查询房源特点
                  String inId = MapUtils.getString(item, "InId", "");
                  List<Object> trait = rdWorderMapper.selectDetailList(Lists.newArrayList(inId.split(",")))
                          .stream().map(tar -> tar.get("InName")).collect(Collectors.toList());
                  if (StringUtils.isNotBlank(MapUtils.getString(item, "Towards"))) {
                      trait.add("朝" + item.get("Towards"));
                  } else {
                      trait.add("朝" + MapUtils.getString(item, "Aspect"));
                      item.put("Towards", MapUtils.getString(item, "Aspect"));
                  }
                  item.remove("Aspect");
                  item.put("trait", trait);

                  item.remove("InId");



                  if(StringUtils.isNotBlank(MapUtils.getString(item,"ShowImg"))){
                      //处理图片
                      item.put("HouImg", item.get("ShowImg"));
                      item.remove("ShowImg");
                  }else{
                      item.put("HouImg", ConstantsHousing.DefaultHousingImg);
                  }


                  return item;
              }).collect(Collectors.toList());


      return getWorderListToday;
  }

  /**
   * 今日需带看的数量
   * @author zhoucong
   * @data 2019/8/7
   * @Param
   * @return
   */
  public Integer getWorderListCountToday(Map<String,Object> params){
      return rdWorderMapper.getWorderListCountToday(params);
  }

  /**
   * 公共转单池
   * @author zhoucong
   * @data 2019/8/8
   * @Param 
   * @return 
   */
  public List<Map<String,Object>> getWorderListPublic(Map<String,Object> params){
      List<Map<String,Object>> list=rdWorderMapper.getWorderListPublic(params);
      if (list.size()>0) {
          //保存转单人的编号
          List<String> OperIdList = new ArrayList<String>();
          for (Map<String, Object> map : list) {
              if (map.get("OperId") != null && !map.get("OperId").equals("")) {
                  //根据 HouId查询房源信息
                  OperIdList.add(map.get("OperId").toString());
              }
          }
          params.put("houIdList", OperIdList);
          System.out.println("houIdList:"+OperIdList);
          //根据编号去网关查询信息
          JsonResult result = baseFeignZuul.getPuserListById(params);
          List<Map<String, Object>> zuulList = (List<Map<String, Object>>)result.get("result");
          if (result.get("errorCode").equals("0")) {
              for (Map<String, Object> map : list) {
                  for (Map<String, Object> map2 : zuulList) {
                      if (MapUtils.getString(map, "OperId").equals(MapUtils.getString(map2, "user_id"))) {
                          map.putAll(map2);
                      }
                  }
              }
          }
      }
      return list;

  }


  /**
   *  公共转单池的数量
   * @author zhoucong
   * @data 2019/8/8
   * @Param
   * @return
   */
  public Integer getWorderListCountPublic(Map<String,Object> params){
      return rdWorderMapper.getWorderListCountPublic(params);
  }


  /**
   * 查询私有转单池
   * @author zhoucong
   * @data 2019/8/8
   * @Param
   * @return
   */
  public List<Map<String,Object>> getWorderListPrivate(Map<String,Object> params){
      List<Map<String,Object>> list=rdWorderMapper.getWorderListPrivate(params);
      if (list.size()>0) {
          //保存转单人的编号
          List<String> OperIdList = new ArrayList<String>();
          for (Map<String, Object> map : list) {
              if (map.get("OperId") != null && !map.get("OperId").equals("")) {
                  //根据 HouId查询房源信息
                  OperIdList.add(map.get("OperId").toString());
              }
          }
          params.put("houIdList", OperIdList);
          System.out.println("houIdList:"+OperIdList);
          //根据编号去网关查询信息
          JsonResult result = baseFeignZuul.getPuserListById(params);
          List<Map<String, Object>> zuulList = (List<Map<String, Object>>)result.get("result");
          if (result.get("errorCode").equals("0")) {
              for (Map<String, Object> map : list) {
                  for (Map<String, Object> map2 : zuulList) {
                      if (MapUtils.getString(map, "OperId").equals(MapUtils.getString(map2, "user_id"))) {
                          map.putAll(map2);
                      }
                  }
              }
          }
      }
      return list;
  }


  /**
   * 私有转单池数量
   * @author zhoucong
   * @data 2019/8/8
   * @Param
   * @return
   */
  public Integer getWorderListCountPrivate(Map<String,Object> params){
      return rdWorderMapper.getWorderListCountPrivate(params);
  }




  /**
   * 创建工单
   * @author zhoucong
   * @data 2019/8/8
   * @Param
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  public JsonResult addWorder(Map<String,Object> params) {
      JsonResult result = new JsonResult();

      /**
       * 加锁操作
       */
      lock.lock();

      try {
          try {
              SysUserVo userVo = ContextUtils.getSysUser();
              ParentDeptVo vo = null;
              for (int i = 0; i < userVo.getLength(); i++) {
                  ParentDeptVo vo1 = userVo.getParentDeptVo();
                  if (vo1.getType().equals(3)) {
                      vo = vo1;
                      break;
                  }
              }
              //客户编号
              Map<String, Object> uuid2 = utilsMapper.getUUID(new HashMap<String, Object>() {{
                  put("uuid", "TenId");
                  put("database", Constants.DATA_SOURCE_TCMKT);
                  put("surface", "tcmkt_tenant");
              }});
              if (uuid2 != null) {
                  int number = Integer.valueOf(uuid2.get("uuid").toString());
                  UUID = ComUtils.getLocalTrmSeqNum("te", number);
              } else {
                  UUID = ComUtils.getLocalTrmSeqNum("te", 0);
              }
              Map<String, Object> map = (Map<String, Object>) params.get("data");
              boolean ifTenant = false;//租客端是否存在该手机号的记录
              if (map.get("TenMode") == null) {
                  return result.putFailed("参数不正确");
              }
              Integer tenCount = rdTenantMapper.getTenantForPactByTenMode(map);//查询后台是否已经创建过租客

              params.put("Phone", map.get("TenMode"));
              params.put("SysId", UUID);
              System.out.println("创建工单发送到我租客端的参数:" + params);
              JsonResult zwxResult = baseFeignTenant.getTctenForTcmkt(params); //去租客端根据手机号查询

              //查询租客端的信息
              if (zwxResult.get("errorCode").toString().equals("0")) {
                  Map<String, Object> zwxMap = (Map<String, Object>) zwxResult.get("result");
                  System.out.println("查询到租客端的数据:" + zwxMap);
                  if (zwxMap != null) {//如果查询到就用租客端的客户编号
                      map.put("TenId", zwxMap.get("SysId"));
                      ifTenant = true;
                  } else {//如果查询不到就用市场部的 客户 编号
                      map.put("TenId", UUID);
                  }
                  System.out.println("zwxMAP" + zwxMap);
              }
              map.put("SetId", ContextUtils.getUserId());//操作人编号
              Map<String, Object> worderMap = rdWorderMapper.getWorderByTenIdSetId(map);//转单的时候根据操作人编号和客户编号查询是否有记录存在
              //工单编号
              Map<String, Object> uuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                  put("uuid", "WoId");
                  put("database", Constants.DATA_SOURCE_TCMKT);
                  put("surface", "tcmkt_worder");
              }});
              System.out.println("uuid:" + uuid);
              if (uuid != null && (!uuid.get("uuid").toString().equals(""))) {
                  int number = Integer.valueOf(uuid.get("uuid").toString());
                  UUID = ComUtils.getLocalTrmSeqNum("wo", number);
              } else {
                  UUID = ComUtils.getLocalTrmSeqNum("wo", 0);
              }
              System.out.println("前端传递的参数:" + params);
              params.put("by", ContextUtils.getUserId());//操作人
              params.put("WoId", UUID);
              params.put("SetId", ContextUtils.getUserId());// 创建工单的人的编号

              params.put("OperId", ContextUtils.getUserId());//接单 操作工单人的编号
              if (vo != null) {
                  params.put("SeId", vo.getDeptId());//接单 操作该工单人的服务中心编号
              }
              params.put("TenStatus", 1);//意向租客状态 1工单带看中 2放弃跟踪
              params.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
              params.put("fnc",
                      this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
              ParamsCommon.commonInsertParms(params);
              params.put("Bind", params.get("instm"));//操作人绑定的时间

              //客户编号
              Map<String, Object> params2 = params;
              System.out.println("前端传递的参数:" + params2);
              params2.put("by", ContextUtils.getUserId());//操作人
              params2.put("TenId", map.get("TenId"));
              params2.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
              params2.put("fnc",
                      this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
              ParamsCommon.commonInsertParms(params2);
              //把客户编号存入工单表中
              params.put("TenId", map.get("TenId"));


              if (map != null) {
                  params.putAll(map);
                  if (params.get("IfSeeing").toString().equals("1")) {
                      params.put("State", 3);//工单状态 0 需带看 1带看中 2 带看完成 3 租客维护 4 换房申请
                  } else {
                      params.put("State", 0);//工单状态 0 需带看 1带看中 2 带看完成 3 租客维护 4 换房申请
                  }
                  System.out.println("转换过后的params:" + params);
                  Integer count = 0;
                  if (worderMap == null) {
                      params.put("TenName", map.get("MakeUserName"));//租客姓名
                      count = rdWorderMapper.addWorder(params);
                  } else {
                      params.put("WoId", worderMap.get("WoId"));
                  }
                  //新增工单详表
                  Map<String, Object> uuid3 = utilsMapper.getUUID(new HashMap<String, Object>() {{
                      put("uuid", "WoInfoId");
                      put("database", Constants.DATA_SOURCE_TCMKT);
                      put("surface", "tcmkt_worder_info");
                  }});
                  System.out.println("uuid:" + uuid3);
                  if (uuid3 != null && (!uuid3.get("uuid").toString().equals(""))) {
                      int number = Integer.valueOf(uuid3.get("uuid").toString());
                      UUID = ComUtils.getLocalTrmSeqNum("wi", number);
                  } else {
                      UUID = ComUtils.getLocalTrmSeqNum("wi", 0);
                  }
                  params.put("WoInfoId", UUID);
                  rdWorderInfoMapper.addWorderInfo(params);
                  if (count > 0 && tenCount == 0) {
                      //把工单编号存入到客户表中
                      params2.put("WoId", params.get("WoId"));
                      params2.putAll(map);
                      System.out.println("params2:" + params2);
                      params2.put("ContactTime", params2.get("instm"));//租客的联系时间
                      rdTenantMapper.addTenant(params2);
                  }
                  result.putSuccess("操作成功");
              } else {
                  result.putFailed("服务器繁忙");
                  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
              }
          } catch (Exception e) {
              result.putFailed("服务器繁忙");
              e.printStackTrace();
              TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
          }
      }

      finally {
        lock.unlock();
    }

  return result;
  }


    /**
     * 在跟客户
     * @author zhoucong
     * @data 2019/8/26
     * @Param
     * @return
     */
    public List<Map<String,Object>> getWorderListMaintain(Map<String,Object> params) {
        return rdWorderMapper.getWorderListMaintain(params);
    }

    /**
     * 在跟客户总数
     * @author zhoucong
     * @data 2019/8/26
     * @Param
     * @return
     */
    public Integer getWorderListCountMaintain(Map<String,Object> params){
        return rdWorderMapper.getWorderListCountMaintain(params);
    }



    /**
     * 创建工单 在客户池点击
     *
     * 创建工单
     *
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addWorderTenant(Map<String, Object> params) {
        JsonResult result=new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try{

            try {
                SysUserVo userVo = ContextUtils.getSysUser();
                ParentDeptVo vo = null;
                for (int i = 0; i < userVo.getLength(); i++) {
                    ParentDeptVo vo1 = userVo.getParentDeptVo();
                    if (vo1.getType().equals(3)) {
                        vo = vo1;
                        break;
                    }
                }
                //工单编号
                params.put("SetId",ContextUtils.getUserId());// 创建工单的人的编号
                if (vo!=null){
                    params.put("SeId",ContextUtils.getUserId());//接单 操作工单人的编号
                }
                params.put("by", ContextUtils.getUserId());//操作人的编号
                params.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                params.put("Bind",params.get("updtm"));//租赁顾问跟工单绑定的时间
                Map<String,Object> map=(Map<String,Object>)params.get("data");
                if (map.get("WoId")==null || map.get("TenId")==null){
                    return result.putFailed("参数不正确");
                }
                if(map!=null){
                    //修改工单的主表
                    params.put("WoId",map.get("WoId"));
                    Integer count1=rdWorderMapper.updateWorder(params);
                    //修改客户的状态
                    params.put("SoId",map.get("SoId"));
                    params.put("TenStatus",1);
                    params.put("TenId",map.get("TenId"));
                    Integer count2=rdTenantMapper.updateTenant(params);
                    //新增一条工单详表的记录
                    Map<String,Object> uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "WoInfoId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_worder_info");
                    }});
                    if(uuid!=null){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        UUID= ComUtils.getLocalTrmSeqNum("wi",number);
                    }else{
                        UUID=ComUtils.getLocalTrmSeqNum("wi",0);
                    }
                    map.put("OperId",ContextUtils.getUserId());
                    map.put("by",map.get("OperId"));//操作人
                    map.put("MakeUserName",params.get("MakeUserName"));//工单姓名
                    map.put("WoInfoId",UUID);
                    map.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    map.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(map);
                    Integer count3=rdWorderInfoMapper.addWorderInfo(map);
                    if (count1>0 && count2>0 &&count3>0){
                        result.putSuccess("操作成功");
                    }else{
                        result.putFailed("服务器繁忙");
                    }
                }else{
                    return result.putFailed("服务器繁忙");
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }


}
